package com.lindroy.todomvp.addtask

import android.app.Activity
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.lindroy.todomvp.R
import com.lindroy.todomvp.util.showSnackBar
import com.lindroy.todomvp.util.textString
import kotlinx.android.synthetic.main.activity_add_edit_task.*
import kotlinx.android.synthetic.main.fragment_add_edit_task.*
import kotlinx.android.synthetic.main.task_item.view.*


class AddEditTaskFragment : Fragment(), AddEditTaskContract.View {

    override lateinit var presenter: AddEditTaskContract.Presenter

    override var isActive: Boolean = false
        get() = isAdded

    override fun showEmptyTaskError() {
        etTaskTitle.showSnackBar(getString(R.string.empty_task_message))
    }

    override fun showTasksList() {
        requireActivity().apply {
            setResult(Activity.RESULT_OK)
            finish()
        }
    }

    override fun setTitle(title: String) {
        etTaskTitle.setText(title)
    }

    override fun setDescription(description: String) {
        etTaskDesc.setText(description)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.fragment_add_edit_task, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        requireActivity().fabEditDone.setOnClickListener {
            presenter.saveTask(etTaskTitle.textString(),etTaskDesc.textString())
        }
    }

    override fun onResume() {
        super.onResume()
        presenter.start()
    }

    companion object {
        const val ARGUMENT_EDIT_TASK_ID = "EDIT_TASK_ID"

        @JvmStatic
        fun newInstance(taskId: String?) =
            AddEditTaskFragment().apply {
                arguments = Bundle().apply {
                    putString(ARGUMENT_EDIT_TASK_ID, taskId)
                }
            }
    }
}